package com.example.database.slice;

import com.example.database.ResourceTable;
import com.example.database.Utils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.data.DatabaseHelper;
import ohos.data.rdb.*;
import ohos.data.resultset.ResultSet;

import java.util.ArrayList;
import java.util.List;

public class RdbAbilitySlice extends AbilitySlice implements Component.ClickedListener {

    private Button mBtnRdbInsert;
    private Button mBtnRdbInsertBatch;
    private Button mBtnRdbQuery;
    private Button mBtnRdbUpdate;
    private Button mBtnRdbDelete;
    private Button mBtnRdbDeleteDatabase;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_rdb);

        mBtnRdbInsert = (Button) findComponentById(ResourceTable.Id_btn_rdb_insert);
        mBtnRdbInsert.setClickedListener(this);
        mBtnRdbInsertBatch = (Button) findComponentById(ResourceTable.Id_btn_rdb_insert_batch);
        mBtnRdbInsertBatch.setClickedListener(this);
        mBtnRdbQuery = (Button) findComponentById(ResourceTable.Id_btn_rdb_query);
        mBtnRdbQuery.setClickedListener(this);
        mBtnRdbUpdate = (Button) findComponentById(ResourceTable.Id_btn_rdb_update);
        mBtnRdbUpdate.setClickedListener(this);
        mBtnRdbDelete = (Button) findComponentById(ResourceTable.Id_btn_rdb_delete);
        mBtnRdbDelete.setClickedListener(this);
        mBtnRdbDeleteDatabase = (Button) findComponentById(ResourceTable.Id_btn_rdb_delete_database);
        mBtnRdbDeleteDatabase.setClickedListener(this);

        // 获取关系型数据库的存储位置
        Utils.log("getDatabaseDir: " + getDatabaseDir().toString());

    }


    @Override
    public void onClick(Component component) {

        if(component.getId() == ResourceTable.Id_btn_rdb_insert) {
            // 获取RdbStore对象
            RdbStore store = getTestRdbStore();

            ValuesBucket values = new ValuesBucket();
            values.putString("name", "董昱");
            values.putInteger("age", 30);
            values.putInteger("sex", 1);
            values.putString("class", "鸿蒙基础学习班");
            long id = store.insert("student", values);
            if (id == -1) {
                Utils.showToast(this, "数据插入失败!");
            } else {
                Utils.showToast(this, "数据插入成功，Row ID: " + id + "!");
            }
            // 使用完毕后要关闭RdbStore对象
            store.close();
        }
        if(component.getId() == ResourceTable.Id_btn_rdb_insert_batch) {
            // 获取RdbStore对象
            RdbStore store = getTestRdbStore();

            List<ValuesBucket> students = new ArrayList<>();
            ValuesBucket student1 = new ValuesBucket();
            student1.putString("name", "王娜");
            student1.putInteger("age", 30);
            student1.putInteger("sex", 0);
            student1.putString("class", "鸿蒙基础学习班");
            students.add(student1);

            ValuesBucket student2 = new ValuesBucket();
            student2.putString("name", "董沐宸松");
            student2.putInteger("age", 20);
            student2.putInteger("sex", 1);
            student2.putString("class", "鸿蒙基础学习班");
            students.add(student2);

            List<Long> ids = store.batchInsertOrThrowException("student", students,
                    RdbStore.ConflictResolution.ON_CONFLICT_ABORT);
            String output = "";
            for(long id : ids) {
                if (id == -1) {
                    Utils.log("数据插入失败!");
                } else {
                    Utils.log("数据插入成功，Row ID: " + id + "!");
                }
            }
            // 使用完毕后要关闭RdbStore对象
            store.close();
        }
        if(component.getId() == ResourceTable.Id_btn_rdb_query) {
            // 获取RdbStore对象
            RdbStore store = getTestRdbStore();

            String[] columns = new String[] {"id", "name", "age", "sex", "class"};
            RdbPredicates rdbPredicates = new RdbPredicates("student")
                    .orderByAsc("id");

            ResultSet resultSet = store.query(rdbPredicates, columns);

            if (resultSet == null) {
                Utils.log("查询失败!");
            }

            Utils.log("结果集行数： " + resultSet.getRowCount());
            while (resultSet.goToNextRow()) {
                int id = resultSet.getInt(0);
                String name = resultSet.getString(1);
                int age = resultSet.getInt(2);
                int sex = resultSet.getInt(3);
                String _class = resultSet.getString(4);
                Utils.log("id:"+id+" 姓名："+name+" 年龄："+ age
                        + " 性别：" + (sex == 1 ? "男性" : "女性")
                        + " 班级：" + _class);
            }
            // 关闭结果集
            resultSet.close();
            // 关闭RdbStore对象
            store.close();
        }
        if(component.getId() == ResourceTable.Id_btn_rdb_update) {
            // 获取RdbStore对象
            RdbStore store = getTestRdbStore();

            RdbPredicates rdbPredicates = new RdbPredicates("student").equalTo("name", "董昱");
            ValuesBucket values = new ValuesBucket();
            values.putString("class", "鸿蒙高级学习班");
            int rowNum = store.update(values, rdbPredicates);
            if (rowNum == -1) {
                Utils.showToast(this, "数据更新失败!");
            } else {
                Utils.showToast(this, "数据更新成功，更新行数: " + rowNum + "!");
            }
            // 使用完毕后要关闭RdbStore对象
            store.close();
        }
        if(component.getId() == ResourceTable.Id_btn_rdb_delete) {
            // 获取RdbStore对象
            RdbStore store = getTestRdbStore();

            RdbPredicates rdbPredicates = new RdbPredicates("student").equalTo("name", "董昱");
            int rowNum = store.delete(rdbPredicates);
            if (rowNum == -1) {
                Utils.showToast(this, "数据删除失败!");
            } else {
                Utils.showToast(this, "数据删除成功，删除行数: " + rowNum + "!");
            }

            store.close();
        }
        if(component.getId() == ResourceTable.Id_btn_rdb_delete_database) {
            // 实例化DatabaseHelper对象
            DatabaseHelper helper = new DatabaseHelper(this);
            // 删除数据库
            boolean flag = helper.deleteRdbStore("test.sqlite");
            if (flag) {
                Utils.showToast(this, "数据库删除成功!");
            } else {
                Utils.showToast(this, "数据库删除失败!");
            }
        }
    }

    /**
     * 获取test.sqlite数据库的RdbStore对象
     * @return RdbStore对象
     */
    private RdbStore getTestRdbStore() {
        // 实例化DatabaseHelper对象
        DatabaseHelper helper = new DatabaseHelper(this);
        // 创建可读写的test.sqlite数据库
        StoreConfig config = StoreConfig.newDefaultConfig("test.sqlite");
        // 获取RdbStore对象，版本号为1
        RdbStore store = helper.getRdbStore(config, 1, new RdbOpenCallback() {
            @Override
            public void onCreate(RdbStore rdbStore) {
                // 在创建test.sqlite数据库时，创建student数据表
                rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (" +
                        "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        "name TEXT NOT NULL, " +
                        "age INTEGER, " +
                        "sex TINYINT, " +
                        "class TEXT)");
            }

            @Override
            public void onUpgrade(RdbStore rdbStore, int i, int i1) {
                // 更新数据库时回调
            }
        });

        return store;
    }
}
